<template>
  <resize-drawer
    :title="drawer.title"
    :drawer="drawer.show"
    :size="1152"
    :isShowMoreBtn="false"
    @onCloseDraw="closeDraw"
  >
    <template #column>
      <Info :row="form" @onUpdateDy="updateDy" @onUpdateOwner="updateOwner" />
      <el-tabs v-model="activeName" style="margin-top: 10px" @tab-click="tabClick">
        <el-tab-pane label="客户详情" name="detail">
          <detail-com ref="DetailCom" @onUpdateData="updateList"></detail-com>
        </el-tab-pane>
        <el-tab-pane label="操作日志" name="log">
          <operate-log ref="OperateLog" :customerId="form._id"></operate-log>
        </el-tab-pane>
      </el-tabs>
    </template>
  </resize-drawer>
</template>

<script lang="ts">
import { defineComponent, getCurrentInstance, nextTick, reactive, onMounted, toRefs } from 'vue'
import resizeDrawer from '@/common/components/resize-drawer/index.vue'
import operateLog from '@/app/customer/components/log/index.vue'
import Info from './info.vue'
import DetailCom from '@app/customer/components/detail.vue'
import { deepClone } from '@/common/utils/common'
import mcCache from '@/common/utils/mc-get-cache'
export default defineComponent({
  name: 'CustomerDetail',
  components: { resizeDrawer, Info, operateLog, DetailCom },
  emits: ['onUpdateData'],
  setup(_, { emit }) {
    const state = reactive({
      drawer: {
        title: '客户详情',
        show: false
      },
      activeName: 'detail',
      form: {} as any
    })

    const instance: any = getCurrentInstance()

    const openDetail = async (row: any) => {
      // 初始化
      state.drawer.show = true
      state.form = deepClone(row)
      await nextTick()
      // 详情表单初始化
      instance?.refs.DetailCom.initData(state.form)
      if (state.activeName === 'log') {
        tabClick(state.activeName)
      }
    }

    const closeDraw = () => {
      // 关闭抽屉
      state.drawer.show = false
    }

    const updateList = () => {
      emit('onUpdateData')
    }

    const tabClick = (tab: any) => {
      if ((tab.props && tab.props.name === 'log') || tab === 'log') {
        instance?.refs.OperateLog.quickQuery()
      }
    }

    const updateDy = async () => {
      await nextTick()
      instance?.refs.DetailCom.updateDyList()
    }

    onMounted(() => {
      mcCache.$getCache('dyForm') // 动态表单（跟进记录、动态表单匹配用到）
    })

    const updateOwner = (owner: string) => {
      state.form.owner = owner
      updateList() // 更新客户池列表
      if (state.activeName === 'log') {
        // 更新日志
        tabClick(state.activeName)
      }
    }

    return {
      closeDraw,
      openDetail,
      updateList,
      tabClick,
      updateDy,
      updateOwner,
      ...toRefs(state)
    }
  }
})
</script>

<style lang="stylus" scoped>
:deep(.el-tabs__header)
  margin 0 0 24px
</style>
